/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;
import handler.database;

/**
 *
 * @author ifan
 */
public class AdminUserServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AdminUserServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet AdminUserServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        int success = 0;
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            int id = 0;
            if(!action.equals("adduser")) {
                id = Integer.parseInt(request.getParameter("id"));
            }
            try {
                if(action.equals("setmod")) {
                    success = setModerator(id);
                } else if(action.equals("unsetmod")) {
                    success = unSetModerator(id);
                } else if(action.equals("ban")) {
                    success = ban(id);
                } else if(action.equals("unban")) {
                    success = unBan(id);
                } else if(action.equals("setroom")) {
                    success = editRoom(id, request.getParameter("room"));
                } else if(action.equals("setemail")) {
                    success = editEmail(id, request.getParameter("email"));
                } else if(action.equals("setpassword")) {
                    success = editPassword(id, request.getParameter("new"), request.getParameter("confirm"));
                } else if(action.equals("adduser")) {
                    success = addUser(request.getParameter("username"), request.getParameter("pass"), request.getParameter("confirm"), request.getParameter("email"));
                } else if(action.equals("deluser")) {
                    success = deleteUser(id);
                }
                if(success==0) {
                    out.println("fail");
                } else {
                    out.println("success");
                }
            } catch (InstantiationException ex) {
                Logger.getLogger(AdminUserServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(AdminUserServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(AdminUserServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(AdminUserServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            out.close();
        }
    }

    private int setModerator(int id) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;
        
        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE user SET role='moderator' WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        conn.close();

        return result;
    }

    private int unSetModerator(int id) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;

        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE user SET role='user' WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        if(result!=0) {
            resetModeratorCategory(id);
        }
        conn.close();

        return result;
    }

    private void resetModeratorCategory(int id) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;

        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE category SET owner_id=0 WHERE owner_id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        conn.close();
    }

    private int ban(int id) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;

        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE user SET ban=1 WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        conn.close();

        return result;
    }

    private int unBan(int id) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;

        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE user SET ban=0 WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        conn.close();

        return result;
    }

    private int editRoom(int id, String numberRoomString) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        int defaultRoom = 25;
        String strQuery = "";
        Statement statement = null;
        int result;
        int numberRoom;
        try {
            numberRoom = Integer.parseInt(numberRoomString);
        } catch (NumberFormatException ex) {
            numberRoom = 25;
        }

        if(numberRoom<1 || numberRoom>defaultRoom) {
            numberRoom = defaultRoom;
        }

        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE user SET max_number_room=" + numberRoom +" WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        conn.close();

        return result;
    }

    private int editEmail(int id, String email) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;

        database db = new database();
        conn = db.getConnection();
        strQuery = "UPDATE user SET email='" + email +"' WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        conn.close();

        return result;
    }

    private int editPassword(int id, String newPass, String confirmPass) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result = 0;

        database db = new database();
        conn = db.getConnection();
        System.out.println(newPass + "," + confirmPass);
        if(newPass.equals(confirmPass)) {
            strQuery = "UPDATE user SET password='" + newPass +"' WHERE id="+id;
            System.out.println(strQuery);
            statement = conn.createStatement();
            result = statement.executeUpdate(strQuery);
            conn.close();
        }

        return result;
    }

    private int addUser(String userName, String pass, String confirmPass, String email) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result = 0;

        database db = new database();
        conn = db.getConnection();
        System.out.println(pass + "," + confirmPass);
        if(pass.equals(confirmPass)) {
            strQuery = "INSERT INTO user (username, password, email, role, max_number_room, ban) "
                        + "VALUES ('"+ userName + "', '"+ pass + "', '" + email + "' , 'user', 25, 0)";
            System.out.println(strQuery);
            statement = conn.createStatement();
            result = statement.executeUpdate(strQuery);
            conn.close();
        }

        return result;
    }

    private int deleteUser(int id) throws InstantiationException, SQLException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        String strQuery = "";
        Statement statement = null;
        int result;

        database db = new database();
        conn = db.getConnection();
        strQuery = "DELETE FROM user WHERE id="+id;
        System.out.println(strQuery);
        statement = conn.createStatement();
        result = statement.executeUpdate(strQuery);
        if(result!=0) {
            resetModeratorCategory(id);
        }
        conn.close();

        return result;
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
